<template>
  <div>
    <!-- breadcrumb-area start -->
    <div class="breadcrumb-area">
      <div class="container">
        <div class="row">
          <div class="col-12">
            <div class="row breadcrumb_box align-items-center">
              <div class="col-lg-6 col-md-6 col-sm-12 text-center text-md-left">
                <h2 class="breadcrumb-title">检查订单</h2>
              </div>
              <div class="col-lg-6 col-md-6 col-sm-12">
                <!-- breadcrumb-list start -->
                <ul class="breadcrumb-list text-center text-md-right">
                  <li class="breadcrumb-item"><router-link to="/">首页</router-link></li>
                  <li class="breadcrumb-item active">检查订单</li>
                </ul>
                <!-- breadcrumb-list end -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- breadcrumb-area end -->

    <!-- checkout area start -->
    <div class="checkout-area pt-100px pb-100px">
      <div class="container">
        <el-row>
          <el-col :offset="6">
            <el-steps
              :active="active - 0"
              finish-status="success"
              align-center
              :space="200"
            >
              <el-step title="查看商品"></el-step>
              <el-step title="选择地址"></el-step>
              <el-step title="下单"></el-step>
            </el-steps>
          </el-col>
        </el-row>
        <el-row>
          <el-tabs
            tab-position="left"
            v-model="active"
            @tab-click="tabClicked"
            :before-leave="beforeTabLeave"
          >
            <el-tab-pane label="查看商品">
              <el-card
                v-for="(item, index) in shop"
                :key="index"
                :body-style="{ padding: '5px' }"
                class="el-card-1"
              >
                <div class="item">
                  <span style="flex: 1; margin-left: 20px">
                    <img :src="$store.state.imgURLPre+item.bookImages" width="110px" height="130px" />
                  </span>

                  <span style="flex: 2">
                    <p>名称：{{ item.bookTitle }}</p>
                    <p>价格：￥{{ item.bookNewPrice }}</p>
                    <p>数量：{{ item.cartAmount }}</p>
                  </span>
                </div>
              </el-card>
            </el-tab-pane>
            <el-tab-pane label="选择地址">
              <el-table
                :data="address"
                border
                stripe
                style="width: 100%"
                id="addressid"
              >
                <el-table-column label="选项" width="100">
                  <template slot-scope="scope">
                    <el-radio v-model="checkAdd" :label="scope.row"
                      >备选项</el-radio
                    >
                  </template>
                </el-table-column>
                <el-table-column
                  prop="addressMessageName"
                  label="收货人姓名"
                ></el-table-column>
                <el-table-column
                  prop="addressMessagePhone"
                  label="电话"
                ></el-table-column>
                <el-table-column
                  prop="addressMessageProvince"
                  label="省"
                ></el-table-column>
                <el-table-column
                  prop="addressMessageCity"
                  label="市"
                ></el-table-column>
                <el-table-column
                  prop="addressMessageDistrict"
                  label="区"
                ></el-table-column>
                <el-table-column
                  prop="addressMessageAddress"
                  label="详细地址"
                ></el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="下单">
              <el-card>
                <el-card class="el-card-1">
                  <div class="item">
                    <span style="flex: 1; margin-left: 20px; font-size: 50px">
                      <i class="el-icon-location"></i>
                    </span>

                    <span style="flex: 2">
                      <p>
                        {{ checkAdd.addressMessageName }}
                        <span style="color: gray">{{
                          checkAdd.addressMessagePhone
                        }}</span>
                      </p>
                      <p>
                        {{
                          checkAdd.addressMessageProvince +
                          checkAdd.addressMessageCity +
                          checkAdd.addressMessageDistrict +
                          checkAdd.addressMessageAddress
                        }}
                      </p>
                    </span>
                  </div>
                </el-card>
                <el-card class="el-card-1">
                  <div v-for="(item, index) in shop" :key="index">
                    <div class="item">
                      <span style="flex: 1; margin-left: 20px">
                        <img
                          :src="$store.state.imgURLPre+item.bookImages"
                          width="110px"
                          height="130px"
                        />
                      </span>

                      <span style="flex: 2">
                        <p>名称：{{ item.bookTitle }}</p>
                        <p>价格：￥{{ item.bookNewPrice }}</p>
                        <p>数量：{{ item.cartAmount }}</p>
                      </span>
                    </div>
                  </div>
                </el-card>
                <el-card class="el-card-1">
                  <div
                    style="
                      display: flex;
                      flex-direction: row;
                      justify-content: end;
                    "
                  >
                    <p>
                      共<span style="color: orange">{{ totalNumber }}</span>
                      件，合计：
                      <span style="color: orange"
                        >￥{{ totalPrice.toFixed(2) }}</span
                      >
                      <el-button
                        type="success"
                        round
                        size="medium"
                        style="margin-left: 20px"
                        @click="addOrder"
                        >提交订单</el-button
                      >
                    </p>
                  </div>
                </el-card>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </div>
    </div>
    <!-- checkout area end -->

    <el-dialog title="支付" :visible.sync="dialogVisible" width="30%">
      <center>
        <img
          src="@/assets/images/banner/wechat.jpg"
          alt=""
          width="400px"
          height="500px"
        />
      </center>
    </el-dialog>
  </div>
</template>

<script>
import API from "@/api/request";
import qs from "qs";
export default {
  name: "BookShopCheckout",

  components: {},

  directives: {},

  data() {
    return {
      active: "0",
      user: {},
      //下单的商品
      shop: [],
      //用户所有的地址
      address: [],
      //选择的地址
      checkAdd: {},
      dialogVisible: false,
      books: [],
      //判断书的数量是否足够
      flag: true,
    };
  },
  computed: {
    
    // 总价
    totalPrice() {
      var price_total = 0;
      for (var i = 0; i < this.shop.length; i++) {
        price_total += this.shop[i].bookNewPrice * this.shop[i].cartAmount;
      }
      return price_total;
    },
    // 总数
    totalNumber() {
      var number_total = 0;
      for (var i = 0; i < this.shop.length; i++) {
        number_total += this.shop[i].cartAmount;
      }
      return number_total;
    },
  },
 
  mounted() {},
  created() {
    this.user = sessionStorage.getItem("user1")
      ? JSON.parse(sessionStorage.getItem("user1"))
      : {};
    this.shop = this.$store.state.checkoutBooks;
    this.getBooks();
    this.getUserById()
  },
  methods: {
    //拿到最新用户信息
    getUserById(){
      API.get("/api/msslyyUser/" + this.user.id).then(
        (res) => {
          if (res.code === "0") {
            this.user = res.data;
            console.log(this.user);
          }
        }
      );
    },
    //批量删除
    deleteCheckout(flag = true) {
      if (this.shop.length > 0) {
        let deleteItems = [];
        this.shop.forEach((e) => {
          deleteItems.push(e.id);
        });
        let carts = JSON.stringify(deleteItems);
        const item = carts.slice(1, -1);
        API.post(`/api/msslyyCart/delete/${item}/${this.user.id}`).then(
          (res) => {
            if (flag) {
              this.$message({
                type: "success",
                message: "批量删除成功",
              });
            }
          }
        );
      }
    },
    //获取所有商品
    getBooks() {
      API.get("/api/msslyyBook").then((res) => {
        this.books = res.data;
        this.shop.forEach((u) => {
          this.books.forEach((b) => {
            //如果id相等且下单数量大于商品数量
            if (
              (u.id === b.id) &
              (u.cartAmount > b.bookQuantityInput - b.bookQuantityOutput)
            ) {
              this.flag = false;
              console.log(this.flag);
            }
          });
        });
      });
    },
    //提交订单
    addOrder() {
      //如果有商品
      if (this.shop.length > 0) {
        this.dialogVisible = true;
        let bookIds = [];
        this.shop.forEach((e) => bookIds.push(e.id));
        bookIds = JSON.stringify(bookIds).slice(1, -1);
        let bookAmounts = [];
        this.shop.forEach((e) => bookAmounts.push(e.cartAmount));
        bookAmounts = JSON.stringify(bookAmounts).slice(1, -1);
        //如果钱不够
        if (this.user.userWallets < this.totalPrice) {
          setTimeout(() => {
            const h = this.$createElement;
            this.$notify.error({
              title: "支付失败",
              message: h("i", { style: "color: teal" }, "您余额不足，请充值~"),
            });
            //返回购物车
            this.$router.push("/shop/cart");
          }, 5000);
        }
        //如果数量不够
        else if (!this.flag) {
          const h = this.$createElement;
          this.$notify({
            title: "支付失败",
            type: 'warning',
            message: h("i", { style: "color: teal" }, "商品数量不足"),
          });
          //返回购物车
          this.$router.push("/shop/cart");
        }
        //钱够数量也够
        else {
          API.post(
            `/api/msslyyOrderMaster/add/${this.user.id}/${this.totalPrice}/${bookIds}/${bookAmounts}`,
            this.checkAdd
          ).then((res) => {
            //支付成功
            if (res.code === "0") {
              this.user.userWallets = this.user.userWallets - this.totalPrice;
              //扣钱
              API.put("/api/msslyyUser/", this.user).then((res) => {});
              //扣数量
              this.shop.forEach((e) => {
                API.post(
                  `/api/msslyyBook/decrQuantity/${e.id}/${e.cartAmount}`
                );
              });

              //增加消费记录
              let wallet = {};
              wallet.userId = this.user.id;
              wallet.walletChange = -this.totalPrice;
              API.post(`/api/msslyyWallet`, wallet);
              //延迟五秒
              setTimeout(() => {
                const h = this.$createElement;
                this.$notify({
                  title: "支付成功",
                  type: 'success',
                  message: h(
                    "i",
                    { style: "color: teal" },
                    "您的订单已经支付成功！！"
                  ),
                });
                this.deleteCheckout(false);
                //返回购物车
                this.$router.push("/");
              }, 5000);
            }
          });
        }

        //如果没有商品
      } else {
        //返回购物车
        this.$router.push("/shop/cart");
      }
    },
    //Tab离开的钩子
    beforeTabLeave(activeName, oldActiveName) {
      if (!this.checkAdd.id & (activeName == 2)) {
        this.$message({
          message: "请先选择地址",
          type: "warning",
        });
        return false;
      }
    },
    //拿到用户所有地址
    getAddress() {
      API.get("/api/msslyyAddressMessaget/findListById/" + this.user.id).then(
        (res) => {
          if (res.code === "0") {
            this.address = res.data;
            console.log(this.address);
          }
        }
      );
    },
    tabClicked() {
      if (this.active == "1") {
        this.getAddress();
      }
    },
    next() {
      if (this.active++ > 2) this.active = 0;
    },
  },
};
</script>

<style  scoped>
.item {
  margin: 10px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.el-row {
  margin-top: 50px;
}
.el-card-1 {
  width: 500px;
  margin-left: 250px;
  margin-bottom: 20px;
}
</style>